<template>
  <div class="label-fees-detail merak-container-has-search">
    <SearchBar
      ref="searchRef"
      v-model="searchForm"
      closeEnter
      closePlan
      @search-event="data => handleSearchToTableParams(data.params)"
    >
      <template #custom_filter>
        <el-select v-model="headerState.value" style="width: 200px" @change="tableRef?.reloadData">
          <el-option v-for="option in headerState.options" :value="option.value" :label="option.label" />
        </el-select>
      </template>
      <template #searchForm>
        <div class="modal-content">
          <div class="modal-title"></div>
          <div class="modal—body">
            <el-scrollbar class="search_from_scrollbar">
              <div class="scrollbar-content">
                <SelectedParams v-model="searchForm" />
                <el-form label-position="top">
                  <el-row :gutter="40">
                    <el-col :span="props.span">
                      <el-form-item prop="apply_order_id" :label="searchForm.apply_order_id.label">
                        <el-input v-model="searchForm.apply_order_id.value" class="qf_input" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="props.span">
                      <el-form-item prop="created_at" :label="searchForm.created_at.label">
                        <el-date-picker
                          v-model="searchForm.created_at.value"
                          class="qf_date"
                          type="daterange"
                          value-format="YYYY-MM-DD"
                          :format="format"
                          :range-separator="$t('merak.rangto')"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="props.span">
                      <el-form-item prop="total_markings" :label="searchForm.total_markings.label">
                        <el-input v-model="searchForm.total_markings.value" class="qf_input" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="props.span">
                      <el-form-item prop="price_km" :label="searchForm.price_km.label">
                        <el-input v-model="searchForm.price_km.value" v-number:4 class="qf_input" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="props.span">
                      <el-form-item prop="marking_price_amount" :label="searchForm.marking_price_amount.label">
                        <el-input v-model="searchForm.marking_price_amount.value" v-number:4 class="qf_input" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="props.span">
                      <el-form-item prop="service" :label="searchForm.service.label">
                        <el-select v-model="searchForm.service.value" class="qf_select">
                          <el-option v-for="option in searchForm.service.options" :value="option.value" :label="option.label" />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="props.span">
                      <el-form-item prop="pay_factory_id" :label="searchForm.pay_factory_id.label">
                        <el-select v-model="searchForm.pay_factory_id.value" class="qf_select">
                          <el-option
                            v-for="option in searchForm.pay_factory_id.options"
                            :value="option.value"
                            :label="option.label"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>
              </div>
            </el-scrollbar>
          </div>
          <div class="modal-footer">
            <el-button @click="handleReset">{{ $t("merak.reset") }}</el-button>
            <el-button type="primary" @click="handleSearch">{{ $t("merak.search") }}</el-button>
            <!-- <el-button type="primary" plain @click="searchRef?.showPlanModal">
              {{ $t("merak.save_search_scheme") }}
            </el-button> -->
          </div>
        </div>
      </template>
    </SearchBar>
    <div class="merak-table-wrapper">
      <MerakXTable
        ref="tableRef"
        v-bind="tableState"
        :enabled-editor-by-auth="!!props.auth?.editOut?.show"
        :queryColumns="handleQueryColumns"
        :queryData="handleQueryData"
        @editor-click="params => Object.assign(tableEditState, { ...params, visible: true })"
      ></MerakXTable>
    </div>
    <el-dialog v-model="tableEditState.visible" width="500px" align-center append-to-body>
      <template #title>
        <div class="editor-title">{{ $t("merak.edit") }}「{{ $t(`marking_labelFees.${tableEditState.field}`) }}」</div>
      </template>
      <el-input v-if="tableEditState.field === 'price_km'" v-model="tableEditState.value" v-num.ponit class="qf_input" />
      <el-select v-if="tableEditState.field === 'pay_factory_id'" v-model="tableEditState.value" class="qf_select">
        <el-option v-for="option in searchForm.pay_factory_id.options" :value="option.value" :label="option.label" />
      </el-select>
      <template #footer>
        <el-button @click="tableEditState.visible = false">{{ $t("merak.cancel") }}</el-button>
        <el-button type="primary" :disabled="!tableEditState.value" :loading="tableEditState.loading" @click="handleSave">
          {{ $t("merak.confirm") }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import type { LabelFeesType, OptionType } from "../index";

import type { UserAuthType } from "@/api/modules/user";

import { getCurrentInstance, ref, reactive, watch, onMounted } from "vue";

import { useRoute } from "vue-router";

import useDateFormat from "@/hooks/useDateFormat";

import useLoading from "@/hooks/useLoading";

import {
  ElButton,
  ElScrollbar,
  ElForm,
  ElFormItem,
  ElRow,
  ElCol,
  ElInput,
  ElSelect,
  ElOption,
  ElDatePicker,
  ElDialog,
  ElMessage
} from "element-plus";

import SearchBar from "@/components/SearchBar/index.vue";

import SelectedParams from "@/components/SearchBar/components/selectedParams.vue";

import MerakXTable, { MerakXTableInstance, MerakXTableProps, MerakXTableEditorParams } from "@/components/MerakXTable";

import { ResultEnum } from "@/enums/httpEnum";
import { getOutlayColumns, getOutlayData, getOutlayOptions, editOutlay } from "@/api/modules/markingManagement/labelFees";

const props = defineProps<{
  currency: LabelFeesType;
  auth: UserAuthType;
  span: number;
}>();

const currentInstance = getCurrentInstance();

const route = useRoute();

const { format } = useDateFormat();

const { queueId, queueLoading } = useLoading();

const tableRef = ref<MerakXTableInstance>();

const searchRef = ref<InstanceType<typeof SearchBar>>();

// 高级搜索头部自定义下拉框相关属性
const headerState = reactive<{
  value?: any;
  options: OptionType[];
}>({
  options: []
});

// 高级搜索表单数据
const searchForm = reactive<
  Record<
    string,
    {
      type: string;
      label?: string;
      value?: any;
      options?: OptionType[];
    }
  >
>({
  apply_order_id: {
    type: "input",
    label: currentInstance?.proxy?.$t("marking_labelFees.apply_order_id")
  },
  created_at: {
    type: "dateTimeRange",
    label: currentInstance?.proxy?.$t("marking_labelFees.created_at")
  },
  total_markings: {
    type: "input",
    label: currentInstance?.proxy?.$t("marking_labelFees.total_markings")
  },
  price_km: {
    type: "input",
    label: currentInstance?.proxy?.$t("marking_labelFees.price_km")
  },
  marking_price_amount: {
    type: "input",
    label: currentInstance?.proxy?.$t("marking_labelFees.marking_price_amount")
  },
  service: {
    type: "select",
    label: currentInstance?.proxy?.$t("marking_labelFees.service")
  },
  pay_factory_id: {
    type: "select",
    label: currentInstance?.proxy?.$t("marking_labelFees.pay_factory_id")
  }
});

// 表格属性
const tableState = reactive<MerakXTableProps>({
  columnsByStore: [],
  toolbar: ["refresh", "export"],
  params: {},
  rowKey: "apply_order_id"
});

// 编辑弹窗属性
const tableEditState = reactive<
  {
    loading: boolean;
    visible: boolean;
  } & Partial<MerakXTableEditorParams>
>({
  loading: false,
  visible: false
});

// 请求列表头
const handleQueryColumns: MerakXTableProps["queryColumns"] = async () => {
  const params: Record<string, any> = {
    supplier_id: route.query.id,
    currency: props.currency
  };
  return getOutlayColumns(params, queueId.value).then(({ code, data }) => {
    if (code == ResultEnum.SUCCESS) {
      tableState.columnsByStore = JSON.parse(JSON.stringify(data.columns));
      searchRef.value?.getPlanList(data.table_id);
      return {
        ...data,
        columns: [...(data.columns ?? [])].map(col => {
          switch (col.field) {
            case "apply_order_id":
              col.fixed = "left";
              break;
            case "import_company_id":
              col.fixed = "left";
              col.slots = { default: ({ row }) => row[`${col.field}_txt`] };
              break;
            case "service":
              col.slots = { default: ({ row }) => row[`${col.field}_txt`] };
              break;
            case "pay_factory_id":
              col.params = { editor: true };
              col.slots = { default: ({ row }) => row[`${col.field}_txt`] };
              break;
            case "price_km":
              col.params = { editor: true };
              break;
            default:
              break;
          }
          return { ...col };
        })
      };
    }
  });
};

// 请求列表数据
const handleQueryData: MerakXTableProps["queryData"] = async ({ page, from }) => {
  const params: Record<string, any> = {
    supplier_id: route.query.id,
    currency: props.currency,
    import_company_id: headerState.value
  };
  if (!!page) {
    Object.assign(params, page);
  }
  if (!!from) {
    Object.assign(params, from);
  }
  return getOutlayData(params, queueId.value).then(({ code, data }) => {
    if (code == ResultEnum.SUCCESS) {
      return { ...data.table_data };
    }
  });
};

// 重置高级搜索
const handleReset = () => {
  Object.values(searchForm).forEach(item => delete item.value);
};

// 高级搜索赋值到表格
const handleSearchToTableParams = (params: Record<string, any>) => {
  if (Array.isArray(params.created_at)) {
    const [created_at_start, created_at_end] = params.created_at;
    Object.assign(params, { created_at_start, created_at_end });
    delete params.created_at;
  }
  tableState.params = { ...params };
};

// 高级搜索
const handleSearch = () => {
  const params: Record<string, any> = searchRef.value?.formParams("value") ?? {};

  handleSearchToTableParams(params);

  searchRef.value?.clear();
  searchRef.value?.modalHide();
};

// 行内编辑保存
const handleSave = () => {
  const params: Record<string, any> = {
    supplier_id: route.query.id,
    currency: props.currency,
    apply_order_id: tableEditState.rowKey,
    import_company_id: headerState.value,
    attribute: tableEditState.field,
    value: tableEditState.value
  };
  tableEditState.loading = true;
  editOutlay(params).then(({ code, data, message }) => {
    tableEditState.loading = false;
    if (code == ResultEnum.SUCCESS) {
      const text =
        tableEditState.field === "pay_factory_id"
          ? searchForm.pay_factory_id.options?.find(option => option.value === tableEditState.value)?.label
          : undefined;
      tableRef.value?.updateCell({
        rowKey: tableEditState.rowKey!,
        field: tableEditState.field!,
        value: tableEditState.value!,
        text
      });
      if (tableEditState.field === "price_km") {
        tableRef.value?.updateCell({
          rowKey: tableEditState.rowKey!,
          field: Object.keys(data)?.[0],
          value: Object.values(data)?.[0]
        });
      }
      tableEditState.visible = false;
      ElMessage.success(currentInstance?.proxy?.$t("marking_labelFees.save_success"));
    } else {
      const msg = typeof message === "object" ? Object.values(message)?.[0] : message;
      ElMessage.error(msg);
    }
  });
};

watch(
  () => headerState.value,
  value => {
    // 获取审核人
    getOutlayOptions({
      supplier_id: route.query.id,
      currency: props.currency,
      import_company_id: value,
      type: "service"
    }).then(({ code, data }) => {
      if (code == ResultEnum.SUCCESS) {
        searchForm.service.options = [...(data.service ?? [])];
      }
    });
    // 获取贴标工厂
    getOutlayOptions({
      supplier_id: route.query.id,
      currency: props.currency,
      import_company_id: value,
      type: "pay_factory_id"
    }).then(({ code, data }) => {
      if (code == ResultEnum.SUCCESS) {
        searchForm.pay_factory_id.options = [...(data.pay_factory_id ?? [])];
      }
    });
  }
);

onMounted(() => {
  // 获取进口公司
  getOutlayOptions({
    supplier_id: route.query.id,
    currency: props.currency,
    type: "importCompany"
  }).then(({ code, data }) => {
    if (code == ResultEnum.SUCCESS) {
      headerState.options = [...(data.importCompany ?? [])];
      headerState.value = headerState.options.at(0)?.value;
    }
  });
});
</script>

<style scoped lang="scss">
.scrollbar-content {
  :deep(.el-form-item__content > *) {
    width: 100%;
  }
}
</style>
